package cn.xl.xxl.imagecache;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.woke.data.Bitmapbakc;
import com.woke.method.MyApp;
import com.woke.method.Util;
import com.zhongcai.online.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.xl.xxl.tools.PictureUtil;

public class ImageLoader {

	private MemoryCache memoryCache = new MemoryCache();
	private static AbstractFileCache fileCache;
	private Map<ImageView, String> imageViews = Collections
			.synchronizedMap(new WeakHashMap<ImageView, String>());
	// �̳߳�
	private static ExecutorService executorService;
	private int REQUIRED_SIZE = 100;
	private Dialog dialog;// �ջ�

	public void setDialog(Dialog dialog) {
		this.dialog = dialog;
	}

	public interface OnLoaderEndListener {
		public void loaderImageEnd();

		public void loaderImageFailed();
	}

	OnLoaderEndListener listener;

	public ImageLoader setOnLoaderEndListener(OnLoaderEndListener l) {
		this.listener = l;
		return this;
	}

	public ImageLoader(Context context) {
		fileCache = new FileCache(context);
		executorService = Executors.newFixedThreadPool(5);
	}

	public void setREQUIRED_SIZE(int rEQUIRED_SIZE) {
		REQUIRED_SIZE = rEQUIRED_SIZE;
	}

	private static ImageLoader imageLoader = null;

	public static ImageLoader getInstance(Context context) {
		if (imageLoader == null) {
			imageLoader = new ImageLoader(context);
		}
		fileCache = new FileCache(context);
		executorService = Executors.newFixedThreadPool(5);
		imageLoader.setREQUIRED_SIZE(150);
		return imageLoader;
	}

	// ����Ҫ�ķ���
	/**
	 * url---ͼƬ���ص�ַ imageview view isLoadOnlyFromCache �������� isRound Բ��ͼƬ
	 * isAdaptation ����ͼƬ
	 * */
	public void DisplayImage(String url, ImageView imageView,
			boolean isLoadOnlyFromCache, boolean isRound, boolean isAdaptation,int bit) {
		imageViews.put(imageView, url);
		// �ȴ��ڴ滺���в���
		Bitmap bitmap = memoryCache.get(url);
		if(url.length() < 10 && isRound == true){
			imageView.setImageResource(R.mipmap.icn__launch_oem);
		}else if(url.length() < 10 && isRound == false){
			imageView.setImageResource(R.drawable.zhongchou_everwhere);
		}else if (bitmap != null) {
			if(bit == 1){
				Bitmapbakc bitm = new Bitmapbakc();
				bitm.bitmap = bitmap;
				EventBus.getDefault().post(bitm);
			}if(bit == 2){
				Bitmapbakc bitm1 = new Bitmapbakc();
				bitm1.bitmap1 = bitmap;
				EventBus.getDefault().post(bitm1);
			}
			if(bit == 4){
				int bitWidth = bitmap.getWidth();
				int bitHeight = bitmap.getHeight();
				int width = MyApp.screenWidth;
				double nScale = (double) (double) width / bitWidth;
				bitHeight = (int) ((double) bitHeight * nScale);
				LayoutParams para = imageView.getLayoutParams();
				if (bitHeight != 0) {
					para.height = bitHeight;
					para.width = width;
				}
				imageView.setLayoutParams(para);
				imageView.setScaleType(ScaleType.FIT_XY);
				imageView.setImageBitmap(bitmap);
			}
			
			if (isRound == true) {
				Bitmap roundBitmap2 = Util.toRoundBitmap(bitmap);
//				Bitmap roundBitmap = Tools.getRoundedCornerBitmap(bitmap);// Բ��ͼƬ
//				if (isAdaptation) {
//					int bitWidth = roundBitmap.getWidth();
//					int bitHeight = roundBitmap.getHeight();
//					int width = MyApplication.getScreenWidth();
//					double nScale = (double) bitWidth / (double) width;
//					bitHeight = (int) ((double) bitHeight / nScale);
//					LayoutParams para = imageView.getLayoutParams();
//					if (bitHeight != 0) {
//						para.height = bitHeight;
//					}
//					imageView.setLayoutParams(para);
//					imageView.setScaleType(ScaleType.FIT_XY);
//				}
				imageView.setImageBitmap(roundBitmap2);
			} else {
				Bitmap roundBitmap2 = Util.toRoundBitmap(bitmap);
//				if (isAdaptation) {
//					int bitWidth = bitmap.getWidth();
//					int bitHeight = bitmap.getHeight();
//					int width = MyApplication.getScreenWidth();
//					double nScale = (double) bitWidth / (double) width;
//					bitHeight = (int) ((double) bitHeight / nScale);
//					LayoutParams para = imageView.getLayoutParams();
//					if (bitHeight != 0) {
//						para.height = bitHeight;
//					}
//					imageView.setLayoutParams(para);
//					imageView.setScaleType(ScaleType.FIT_XY);
//				}
				imageView.setImageBitmap(bitmap);
			}
			if (listener != null) {
				this.listener.loaderImageEnd();
			}
			imageView.setVisibility(View.VISIBLE);
			if (dialog != null) {
				dialog.cancel();
			}
		} else if (!isLoadOnlyFromCache) {

			// ��û�еĻ��������̼߳���ͼƬ
			queuePhoto(url, imageView, isRound, isAdaptation,bit);
		}
	}

	public void DisplayImagePhoto(String url, ImageView imageView,
			boolean isLoadOnlyFromCache, boolean isRound, boolean isAdaptation,int bit) {
		int end = url.lastIndexOf("/");
		String photoName = url.substring(end + 1);
		String imageFileName = "xxl_" + photoName + ".jpg";
		File f = new File(PictureUtil.getAlbumDir(), imageFileName);
		if (f != null && f.exists()) {
			String imagePath = f.getAbsolutePath();
			imageView.setImageBitmap(PictureUtil.getSmallBitmap(imagePath));
			return;
		} else {
//			Log.e("ͼƬ������", "ͼƬ������");
			DisplayImage(url, imageView, isLoadOnlyFromCache, isRound,
					isAdaptation,bit);
		}

	}

	public Bitmap getBitmap1(final String url) {
		Bitmap bitmap = memoryCache.get(url);
		if (bitmap != null) {
			return bitmap;
		}
		return null;
	}
	
	public Bitmap getFileBitmap(String url) {
		File f = fileCache.getFile(url);
		// �ȴ��ļ������в����Ƿ���
		Bitmap b = null;
		if (f != null && f.exists()) {
			b = decodeFile(f,false);
		}
		if (b != null) {
			return b;
		}
		return null;
	}

	public String getImageFile(final String url) {
		File f = fileCache.getFile(url);
		if (f != null && f.exists()) {
			return f.getAbsolutePath();
		}
		return null;
	}

	private void queuePhoto(String url, ImageView imageView, boolean isRound,
			boolean isAdaptation,int bit) {
		PhotoToLoad p = new PhotoToLoad(url, imageView);
		executorService.submit(new PhotosLoader(p, isRound, isAdaptation,bit,imageView));
	}

	private Bitmap getBitmap(String url, boolean isAdaptation) {
		File f = fileCache.getFile(url);
		// �ȴ��ļ������в����Ƿ���
		Bitmap b = null;
		if (f != null && f.exists()) {
			b = decodeFile(f,isAdaptation);
		}
		if (b != null) {
			return b;
		}
		// ����ָ����url������ͼƬ
		try {
			Bitmap bitmap = null;
			URL imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setInstanceFollowRedirects(true);
			InputStream is = conn.getInputStream();
			OutputStream os = new FileOutputStream(f);
			CopyStream(is, os);
			os.close();
			is.close();
			bitmap = decodeFile(f,isAdaptation);
			conn.disconnect();
			return bitmap;
		} catch (Exception ex) {
			Log.e("",
					"getBitmap catch Exception...\nmessage = "
							+ ex.getMessage());
			return null;
		}

	}

	public Bitmap getBitmapByte(byte[] bs, String imgName) {
		File f = fileCache.getFile(imgName);
		Bitmap b = null;
		if (f != null && f.exists()) {
			b = decodeFile(f,false);
		}
		if (b != null) {
			return b;
		}
		// ����ָ����url������ͼƬ
		try {
			Bitmap bitmap = null;
			OutputStream os = new FileOutputStream(f);
			os.write(bs);
			os.close();
			bitmap = decodeFile(f,false);
			return bitmap;
		} catch (Exception ex) {
			Log.e("",
					"getBitmap catch Exception...\nmessage = "
							+ ex.getMessage());
			return null;
		}

	}

	// decode���ͼƬ���Ұ����������Լ����ڴ���ģ�������ÿ��ͼƬ�Ļ����СҲ�������Ƶ�
	private Bitmap decodeFile(File f, boolean isAdaptation) {
		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);
			// Find the correct scale value. It should be the power of 2.
			// final int REQUIRED_SIZE = 100;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
//			Log.e("Ǯ���"+height_tmp, "Ǯ��"+width_tmp);
			int imageSize = (int) (f.length() / 1024.0);
			int scale = 1;
			while (true) {
				if (imageSize < REQUIRED_SIZE)
					break;
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale = 2;
//				if(isAdaptation == true){
//					scale = 2;
//				}else{
//					scale = 3;
//				}
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
//			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
			Bitmap decodeStream = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
			decodeStream.getHeight();
			return decodeStream;
		} catch (FileNotFoundException e) {
			
		}catch (OutOfMemoryError err) {
		}
		return null;
	}

	// Task for the queue
	private class PhotoToLoad {
		public String url;
		public ImageView imageView;

		public PhotoToLoad(String u, ImageView i) {
			url = u;
			imageView = i;
		}
	}

	class PhotosLoader implements Runnable {
		PhotoToLoad photoToLoad;
		boolean isRound = false;
		boolean isAdaptation = false;
		int bit = 0;
		ImageView imageView;

		PhotosLoader(PhotoToLoad photoToLoad, boolean isRound,
				boolean isAdaptation,int bit, ImageView imageView) {
			this.photoToLoad = photoToLoad;
			this.isRound = isRound;
			this.isAdaptation = isAdaptation;
			this.bit = bit;
			this.imageView = imageView;
		}

		@Override
		public void run() {
			if (imageViewReused(photoToLoad))
				return;
			Bitmap bmp = getBitmap(photoToLoad.url,isAdaptation);
			if(bit == 1){
				Bitmapbakc bitm = new Bitmapbakc();
				bitm.bitmap = bmp;
				EventBus.getDefault().post(bitm);
			}if(bit == 2){
				Bitmapbakc bitm1 = new Bitmapbakc();
				bitm1.bitmap1 = bmp;
				EventBus.getDefault().post(bitm1);
			}
			memoryCache.put(photoToLoad.url, bmp);
			if (imageViewReused(photoToLoad))
				return;
			BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad, isRound,
					isAdaptation,bit,imageView);
			// ���µĲ�������UI�߳���
			Activity a = (Activity) photoToLoad.imageView.getContext();
			a.runOnUiThread(bd);
		}
	}

	/**
	 * ��ֹͼƬ��λ
	 * 
	 * @param photoToLoad
	 * @return
	 */
	boolean imageViewReused(PhotoToLoad photoToLoad) {
		String tag = imageViews.get(photoToLoad.imageView);
		if (tag == null || !tag.equals(photoToLoad.url))
			return true;
		return false;
	}

	// ������UI�߳��и��½���
	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		PhotoToLoad photoToLoad;
		boolean isRound = false;
		boolean isAdaptation = false;
		int bit ;
		ImageView imageView;

		public BitmapDisplayer(Bitmap b, PhotoToLoad p, boolean isRound,
				boolean isAdaptation, int bit, ImageView imageView) {
			bitmap = b;
			photoToLoad = p;
			this.isRound = isRound;
			this.isAdaptation = isAdaptation;
			this.bit = bit;
			this.imageView = imageView;
		}

		public void run() {
			if (imageViewReused(photoToLoad))
				return;
			if (bitmap != null) {
				if (isRound == true) {
					Bitmap roundBitmap2 = Util.toRoundBitmap(bitmap);
//					Bitmap roundBitmap = Tools.getRoundedCornerBitmap(bitmap);
//					if (isAdaptation) {
//						int bitWidth = roundBitmap.getWidth();
//						int bitHeight = roundBitmap.getHeight();
//						int width = MyApplication.getScreenWidth();
//						double nScale = (double) bitWidth / (double) width;
//						bitHeight = (int) ((double) bitHeight / nScale);
//						LayoutParams para = photoToLoad.imageView
//								.getLayoutParams();
//						para.height = bitHeight;
//						photoToLoad.imageView.setLayoutParams(para);
//						photoToLoad.imageView.setScaleType(ScaleType.FIT_XY);
//					}
					photoToLoad.imageView.setImageBitmap(roundBitmap2);
				} else {
//					if (isAdaptation) {
//						int bitWidth = bitmap.getWidth();
//						int bitHeight = bitmap.getHeight();
//						int width = MyApplication.getScreenWidth();
//						double nScale = (double) bitWidth / (double) width;
//						bitHeight = (int) ((double) bitHeight / nScale);
//						LayoutParams para = photoToLoad.imageView
//								.getLayoutParams();
//						if (bitHeight != 0) {
//							para.height = bitHeight;
//						}
//						photoToLoad.imageView.setLayoutParams(para);
//						photoToLoad.imageView.setScaleType(ScaleType.FIT_XY);
//					}
					
					if(bit == 4){
						int bitWidth = bitmap.getWidth();
						int bitHeight = bitmap.getHeight();
						int width = MyApp.screenWidth;
						double nScale = (double) (double) width / bitWidth;
						bitHeight = (int) ((double) bitHeight * nScale);
						LayoutParams para = imageView.getLayoutParams();
						if (bitHeight != 0) {
							para.height = bitHeight;
							para.width = width;
						}
						imageView.setLayoutParams(para);
						imageView.setScaleType(ScaleType.FIT_XY);
					}
					
					photoToLoad.imageView.setImageBitmap(bitmap);
				}
				if (listener != null) {

					listener.loaderImageEnd();
				}
				photoToLoad.imageView.setVisibility(View.VISIBLE);
			} else {
				if (listener != null) {

					listener.loaderImageFailed();
				}

			}
			if (dialog != null) {
				dialog.cancel();
			}
		}
	}

	public void deleteImage(String url) {
		File f = fileCache.getFile(url);
		if (f != null && f.exists()) {
			fileCache.deleteImage(f.toString());
		}
	}

	public void clearCache() {
		memoryCache.clear();
		fileCache.clear();
	}

	public void clearMemoryCache() {
		memoryCache.clear();
	}

	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
			Log.e("", "CopyStream catch Exception...");
		}
	}

	/**
	 * ��ȡ����ͼƬ
	 * 
	 * */

	public interface DownImage {
		public void imageLoader(Bitmap pic);
	}

	DownImage downImage;

	public ImageLoader setLoader(DownImage downImage) {
		this.downImage = downImage;
		return this;

	}

	public void getLogBitmap(final String imagePath) {
		Bitmap bitmap = memoryCache.get(imagePath);
		if (bitmap != null) {
			downImage.imageLoader(bitmap);
			return;
		}
		final File f = fileCache.getFile(imagePath);
		Bitmap b = null;
		if (f != null && f.exists()) {
			b = decodeFile(f,false);
		}
		if (b != null) {
			if (downImage != null) {
				downImage.imageLoader(b);
			}

			return;
		}
		new Thread(new Runnable() {
			@Override
			public void run() {
				Bitmap pic = null;
				try {
					String url = imagePath.replaceAll(" ", "%20");
					HttpGet get = new HttpGet(url);
					HttpClient client = new DefaultHttpClient();
					HttpResponse response = client.execute(get);
					HttpEntity entity = response.getEntity();
					InputStream is = entity.getContent();
					OutputStream os = new FileOutputStream(f);
					CopyStream(is, os);
					os.close();
					is.close();
					pic = decodeFile(f,false); // �ؼ���������
				} catch (ClientProtocolException e) {
					e.printStackTrace();
					if (downImage != null) {
						downImage.imageLoader(null);
					}

				} catch (IOException e) {
					e.printStackTrace();
					if (downImage != null) {
						downImage.imageLoader(null);
					}

				}
				if (downImage != null) {
					downImage.imageLoader(pic);
				}

				memoryCache.put(imagePath, pic);

			}
		}).start();
	}

}